<template>
  <div class='header'>

    <span>司机发布行程</span>

  </div>
  <div class='form'>
    <el-form :model="form" label-width="120px">
      <el-form-item label="行程路线">
        <el-select v-model="option" placeholder="请选择您的出发路线" @change="change(option)">
          <el-option v-for="(item, index) in options" :key="index" :label="item.name" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="拼车价格">
        <div>{{ price }}</div>
      </el-form-item>
      <el-form-item label="出发日期">
        <el-radio-group v-model="date" size="large">
          <el-radio-button label="今天"/>
          <el-radio-button label="明天"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出发时间">
        <el-col :span="15">
          <el-time-select v-model="form.start_time" end="24:00" placeholder="请选择出发时间" start="06:00"
                          step="00:30"/>
        </el-col>
      </el-form-item>
      <el-form-item label="最大可载人数">
        <el-radio-group v-model="form.max_seat_capacity">
          <el-radio-button v-for="(item, index) in NumArr" :key="index" :label="item"/>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <div class="btn">
      <el-button type="primary" @click="onSubmitDebounced">确认发布</el-button>
      <el-button @click="cancel">取消发布</el-button>
    </div>
  </div>
</template>
<script setup>
import {ref} from 'vue'
import {debounce} from 'lodash';
import request from "@/utils/request";
import {useRouter} from 'vue-router';

const userInfo = ref({});
const router = useRouter();
//行程关联价格
const options = [
  {name: '火车站-学校', cost: 50, id: 1},
  {name: '学校-火车站', cost: 50, id: 2},
  {name: '学校-飞机场', cost: 80, id: 3},
  {name: '飞机场-学校', cost: 80, id: 4},
]

const date = ref('');
const price = ref('');
const option = ref();
const NumArr = [1, 2, 3, 4, 5, 6, 7, 8]
// form表单
const form = ref({
  vehicle_id: 0,
  name: '',
  username: '',
  phone: '',
  vehicle_license: '',
  start_time: '',
  start_date: '',
  num_passengers: 0,
  max_seat_capacity: '',
  status: '等待乘客',
  vehicle_route_id: '',
})

//判断form里面是否有为空的属性
const isEmpty = ref(false);

function checkEmptyProperties(obj) {
  // 遍历对象的每个属性
  for (let key in obj) {
    // 如果属性值为对象，则递归检查其子属性
    if (typeof obj[key] === 'object') {
      checkEmptyProperties(obj[key]);
    } else {
      // 如果属性值为空字符串或为null，则认为该属性为空
      if (obj[key] === '' || obj[key] === null) {
        isEmpty.value = true;
      }
    }
  }
}

//调用接口
const deliver = (data) => {
  request.post("/vehicle-trip/vehicleTrip/deliver", data).then(result => {
        if (result.success) {
          console.log(result.message)
        }
      }
  )
}


//获取本地用户信息
const parseUserInfo = () => {
  const originalString = localStorage.getItem("user")
  var newStr = originalString.substring(31, originalString.length - 1); // 从索引12开始，截取到字符串末尾的前一个字符，即去掉 "]"
  // 去掉字符串两侧的空格，并替换其中的等号和单引号为对应的JSON字符
  var newStr = newStr.replace(/=/g, ':').replace(/'/g, '"');
  // 在字符串开头和结尾添加大括号，使其成为一个完整的JSON对象
  let pairs = newStr.split(", ");
  let jsonObj = {};
  for (let i = 0; i < pairs.length; i++) {
    let keyValuePair = pairs[i].split(":");
    jsonObj[keyValuePair[0]] = keyValuePair[1];
  }
  let jsonStr = JSON.stringify(jsonObj);
  userInfo.value = JSON.parse(jsonStr);
}


parseUserInfo();

//发布
const onSubmit = () => {

  if (date.value == '今天') {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate());
    const year = tomorrow.getFullYear();
    const month = tomorrow.getMonth() + 1; // getMonth() 返回的月份从 0 开始，所以需要加 1
    const date = tomorrow.getDate();
    form.value.start_date = `${year}-${month < 10 ? '0' + month : month}-${date < 10 ? '0' + date : date}`;
  } else if (date.value == '明天') {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1); // 增加一天
    const year = tomorrow.getFullYear();
    const month = tomorrow.getMonth() + 1; // getMonth() 返回的月份从 0 开始，所以需要加 1
    const date = tomorrow.getDate();
    form.value.start_date = `${year}-${month < 10 ? '0' + month : month}-${date < 10 ? '0' + date : date}`;
  }
  if (form.value.start_time != '') {
    form.value.start_time = form.value.start_time + ":00"
  }


  //将用户的基本信息提交给form
  if (localStorage.getItem("user") != null) {
    form.value.vehicle_id = localStorage.getItem("userId");
    form.value.name = userInfo.value.name;
    form.value.username = userInfo.value.username;
    form.value.phone = userInfo.value.phone;
    form.value.vehicle_license = userInfo.value.vehicleLicense;
  }

  console.log(form.value);
  //判断form对象中是否有空的数据
  checkEmptyProperties(form);
  if (isEmpty.value === false) {
    //调用发布行程接口

    deliver(form.value);

    ElMessage({
      message: '发布行程成功',
      type: 'success',
    })
    router.push("/mytrip")
  } else {
    ElMessage({
      message: '发布内容不能为空',
      type: 'error',
    })
  }

  cancel();

}

//取消进行清空
const cancel = () => {
  form.value.start_time = '';
  form.value.start_date = '';
  form.value.max_seat_capacity = '';
  form.value.vehicle_route_id = '';
  option.value = '';
  price.value = '';
  date.value = '';
}
//异常处理
const change = (item) => {
  option.value = item.name
  price.value = item.cost
  form.value.vehicle_route_id = item.id;
}


const onSubmitDebounced = debounce(onSubmit, 500) // 延迟300毫秒后触发一次
</script>
<style lang='less' scoped>
.header {
  text-align: center;
  background-color: #BDDCFF;
  height: 60px;
  line-height: 60px;
  color: #495e77;

}

.form {
  width: 100%;

  .el-form {
    .el-form-item {
      height: 120px;
      border-bottom: 1px solid #D4D4D4;
      margin: 0;
    }

    :deep(.el-form-item__label) {
      line-height: 120px !important;
    }

  }
}

.btn {
  text-align: center;
  line-height: 100px;
}

.el-radio-button {
  margin-right: 10px;
}
</style>
